var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var app = getApp();

Page({
  data: {
    util: util,
    orgInfo: '',
    org_name: '',
    bottom_nav_data: [],
    isIphone_x: false,
  
    screen_w: 320,
    screen_h: 480,

    photo_w: 90,
    photo_h: 135,

    video_w: 140,
    video_h: 92,

    msg_img_w: 290,
    msg_img_h: 110,

    userInfo: '',
    photoArr: [],
    videoArr: [],

    zhaValue: 0,
    zanValue: 0,
    zhaProgress_w: 10,
    zanProgress_w: 10,

    isFromChat: false,

    isShop: false,

    showVideo: false
  },

  cuid: 0,
  inviteuid: '',
  userPhotos: [],

  maxProgress_w: 200,
  min_meili_count: 168,
  max_meili_count: 888,

  lastZanDayKey: 'lastZanKey',//最后一次赞这个用户的缓存时间key，只做本地缓存，一天只能操作一次
  lastCaiDayKey: 'lastCaiKey',//最后一次踩这个用户的缓存时间key，只做本地缓存，一天只能操作一次

  onLoad: function (data) {
    console.log("user qrcode data:", data)
    this.cuid = data.uid
    this.lastZanDayKey = 'lastZanKey' + data.uid
    this.lastCaiDayKey = 'lastCaiKey' + data.uid

    this.maxProgress_w = app.screen_w - 163;
    var p_w = (app.screen_w - 50) / 3;
    this.setData({
      isIphone_x: app.isIphone_x,
      screen_w: app.screen_w,
      screen_h: app.screen_h,
      photo_w: p_w,
      photo_h: p_w * 1.5,
      video_w: (app.screen_w - 40)/2,
      video_h: (app.screen_w - 40)/2 * 0.5625,
      msg_img_w: app.screen_w,
      msg_img_h: (app.screen_w - 30) * 0.378,
      zhaProgress_w: this.maxProgress_w,
      isFromChat: data.fromchat ? true : false,
      isShop: data.isshop? true : false
    });

    if (data.isshop) {
      this.getShopDetail()
    } else {
      this.getThisUserInfo()
    }

    this.getLoginUserInfo()

    var that = this
    app.getWxCheck(function(show) {
      that.setData({
        showVideo: show
      })
    })
  },

  getLoginUserInfo: function() {
    //读取登录用户信息
    var that = this
    app.LoginUserInfo(function (res) {
      console.log("登录用户信息：", res);
      if (res == '-1') {
        tt.showToast({
          title: '授权登录失败',
        })
      } else if(res == '-2') {
        tt.showToast({
          title: '网络异常',
        })
      } else {
        that.addLookMeOrMeLookRecord()
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  onShow: function () {
    
  },

  resetNavColor: function () {
    var bg_color = '#d8202d';
    var fg_color = '#ffffff';
    if (this.data.colorSet) {
      var colorJO = this.data.colorSet;
      bg_color = colorJO.titlebg;
      fg_color = colorJO.titlefont;
    }
    tt.setNavigationBarColor({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
  },

  goAtherPage: function (e) {
    console.log("goAtherPage!!!!!!!!");
    var url = e.currentTarget.dataset.link;
    tt.navigateTo({
      url: url
    })
  },
  goAtherPageRedirect: function (e) {
    var url = e.currentTarget.dataset.link;
    tt.redirectTo({
      url: url
    })
  },

  //底部导航跳转
  navigtionClick: function (e) {
    console.log("点击参数：", e);
    var path = e.currentTarget.dataset.path;
    console.log("跳转连接信息：", path);
    if (path) {
      if (path.indexOf('navto:') == 0) {
        var navPath = path.slice(6);
        tt.navigateTo({
          url: navPath,
        })
      } else {
        tt.redirectTo({
          url: path
        });
      }
    }
  },

    getShopDetail: function () {
    // http://admin.jawanology.com/go.php?ac=getShopDetail&uid=220581&publickey=ZGZvI1mi8Q
    var that = this;
    var params = {
      publickey: util.publiccode,
      ac: "getShopDetail",
      uid: that.cuid
    }
    util.api_go({
      data: params,
      success: function (responseData) {
        console.log("供货商详情：", responseData);
        var res = responseData.data;
        if (!res.msg) {
          let photos = []
          if (res.photo && res.photo.length > 0) {
            let photoArr = res.photo.split(',')
            that.userPhotos = []
            photoArr.forEach(function(m) {
              let photoOb = {}
              photoOb.pass = '1'
              photoOb.url = m
              photos = photos.concat(photoOb) 
              that.userPhotos = that.userPhotos.concat(m)
            })
          }
          that.setData({
            userInfo: res,
            photoArr: photos
          });
          
          that.getAllUpladedVideos(true)

          let userBad = (res.userbad && res.userbad.length > 0) ? parseInt(res.userbad) : 0
          let userRec = (res.userrec && res.userrec.length > 0) ? parseInt(res.userrec) : 0
          that.calculateMeili(userBad, userRec);
        }
      
      }
    });
  },

  getThisUserInfo: function () {
    var that = this;
    //读取登录用户信息
    app.getUserInfo(that.cuid, function (res) {
      console.log("个人详情资料：", res)
      if (res && res != -1) {
        tt.setNavigationBarTitle({
          title: res.uname + "的资料"
        })
        that.setData({
          userInfo: res
        });
        that.getAllUpladedImages(true)
        that.getAllUpladedVideos(true)

        let userBad = (res.userbad && res.userbad.length > 0) ? parseInt(res.userbad) : 0
        let userRec = (res.userrec && res.userrec.length > 0) ? parseInt(res.userrec) : 0
        that.calculateMeili(userBad, userRec);
      }
    });
  },

  //获取该用户所有已上传的图片信息
  getAllUpladedImages: function(reget = false) {
    var that = this;
    app.getAllUpladedImages(that.cuid, reget, function(res){
      if(res != 0 && res != -1) {
        that.userPhotos = []
        res.forEach(function(m){
          that.userPhotos = that.userPhotos.concat(m.url)
        })
        console.log("用户相册链接数组：", that.userPhotos);
        that.setData({
          photoArr: res,
        })
      }
    })
  },

  //获取该用户所有已上传的视频信息
  getAllUpladedVideos: function(reget = false) {
    var that = this;
    app.getAllUpladedvideos(that.cuid, reget, function(res){
      if(res != 0 && res != -1) {
        that.setData({
          videoArr: res,
        })
      }
      tt.hideLoading();
    })
  },

  calculateMeili: function(zhaVal, zanVal){
    let maxValue = zhaVal > zanVal ? zhaVal : zanVal
    maxValue = maxValue < 100 ? 100 : maxValue
    this.setData({
      zhaProgress_w: this.maxProgress_w * zhaVal / maxValue,
      zanProgress_w: this.maxProgress_w * zanVal / maxValue,
      zhaValue: zhaVal > 9999 ? '9999+' : zhaVal,
      zanValue: zanVal > 9999 ? '9999+' : zanVal,
    })
  },

  showBigPhoto: function(e) {
    let photoIndex = e.currentTarget.dataset.index
    console.log("显示大图：" + photoIndex, e)
    var that = this
    tt.previewImage({
      current: that.userPhotos[photoIndex],
      urls: that.userPhotos
    })
  },


  //点赞
  gooduserAction: function() {
    if(!app.globalData.cuid || !app.globalData.token) {
      this.showLogoutModal()
      return
    }
    if(app.globalData.cuid == this.cuid) {
      console.log("看自己的详情页，不打招呼")
      tt.showToast({
        title: '你看的是自己',
      })
      return
    }
    let lastZanDay = tt.getStorageSync(this.lastZanDayKey)
    var day = new Date().getDay()
    if(lastZanDay == day){
      tt.showToast({
        title: '今天已经赞过了',
      })
      return
    }
    var that = this;
    let privateKey = utilMd5.hexMD5(app.globalData.cuid + "gooduser" + app.globalData.token);
    let commitData = {
      "privatekey": privateKey,
      "ac": "gooduser",
      "uid": app.globalData.cuid,
      "douid": that.cuid
    };
    console.log("赞用户：", commitData)
    util.api_go({
      data: commitData,
      method: "POST",
      success: function(responseData) {
        console.log("赞用户返回：", responseData);
        if (responseData.data.res) {
          //保存成功
          tt.showToast({
            title: "点赞成功",
          })
          that.calculateMeili(that.data.zhaValue, that.data.zanValue + 1)
          tt.setStorage({
            key: that.lastZanDayKey,
            data: day
          })
        } else {
          tt.showToast({
            title: responseData.data.msg,
          })
        }
      }
    });
  },

  //踩一下
  baduserAction: function() {
    if(!app.globalData.cuid || !app.globalData.token) {
      this.showLogoutModal()
      return
    }
    if(app.globalData.cuid == this.cuid) {
      console.log("看自己的详情页，不打招呼")
      tt.showToast({
        title: '你看的是自己',
      })
      return
    }

    let lastCaiDay = tt.getStorageSync(this.lastCaiDayKey)
    var day = new Date().getDay()
    if(lastCaiDay == day){
      tt.showToast({
        title: '今天已经踩过了',
      })
      return
    }
    var that = this;
    let privateKey = utilMd5.hexMD5(app.globalData.cuid + "baduser" + app.globalData.token);
    let commitData = {
      "privatekey": privateKey,
      "ac": "baduser",
      "uid": app.globalData.cuid,
      "douid": that.cuid
    };
    console.log("踩用户：", commitData)
    util.api_go({
      data: commitData,
      method: "POST",
      success: function(responseData) {
        console.log("踩用户返回：", responseData);
        if (responseData.data.res) {
          //保存成功
          tt.showToast({
            title: "踩了一脚",
          })
          that.calculateMeili(that.data.zhaValue + 1, that.data.zanValue)
          tt.setStorage({
            key: that.lastCaiDayKey,
            data: day
          })
        } else {
          tt.showToast({
            title: responseData.data.msg,
          })
        }
      }
    });
  },

  showLogoutModal: function() {
    var that = this
    tt.showModal({
      title: '温馨提示',
      content: '您还未授权登录',
      confirmText: "授权",
      complete: (res) => {
        if (res.confirm) {
          that.getLoginUserInfo()
        }
      }
    })
  },

  makeCall: function (e) {
    tt.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.number
    })
  },

  sendHelloMessage: function () {
    // post请求，ac=postmsg，传入uid-发送者uid，touid-接收者uid，msg-消息内容。返回操作成功/失败。调用成功后 会增加消息列表接口中的未读数量
    var that = this;
    if(!app.globalData.cuid || !app.globalData.token) {
      this.showLogoutModal()
      return
    }
    if(app.globalData.cuid == that.cuid) {
      console.log("看自己的详情页，不打招呼")
      tt.showToast({
        title: '你看的是自己',
      })
      return
    }

    if (!that.cuid || that.cuid == '0') {
      tt.showToast({
        title: '该用户已消失',
      })
      return
    }

    let noGetSubMsg = app.noSubscribeMessageCache()
    console.log("已经授权订阅消息：" + noGetSubMsg)
    if (noGetSubMsg) {
      tt.requestSubscribeMessage({
        tmplIds: [app.globalData.tmplMsgIds],
        success(res) {
          console.log("订阅消息结果：", res)
          if (res.errMsg.indexOf(":ok") > 0) {
            app.setSubscribeMessageCache()
          }
        }
      })
    }
    
    tt.navigateTo({
      url: '/pages/chatMessage/chatMessage?sayhello=true&uid=' + that.cuid
    })
  },

  addLookMeOrMeLookRecord: function () {
    var that = this
    if(app.globalData.cuid == that.cuid) {
      console.log("看自己的详情页，不添加查看记录")
      return
    }
    let privateKey = utilMd5.hexMD5(app.globalData.cuid + "postmsg" + app.globalData.token);
    let commitData = {
      "privatekey": privateKey,
      "ac": "recordLookme",
      "uid": app.globalData.cuid,
      "kanuid": that.cuid
    };
    console.log("添加查看记录：", commitData)
    util.api_go({
      data: commitData,
      method: "POST",
      success: function(responseData) {
        console.log("添加查看记录返回：", responseData);
      }
    });
  },

  //页面分享
  onShareAppMessage: function () {
    var that = this;
    var shareTitle = "我觉得 " + that.data.userInfo.uname + " 很不错，可以认识一下，马上进去聊天吧！"
    var sharePath = '/pages/launch/launch?share=true&uid=' + that.cuid
    if (!that.data.showVideo) {
      shareTitle = "朋友，我发现一些美食和好住处"
      sharePath = '/pages/index/index'
    }
    var shareImgUrl = that.getShareImgUrl()
    return {
      title: shareTitle,
      imageUrl: shareImgUrl,
      path: sharePath
    }
  },
  
  getShareImgUrl() {
    for (var i = 0; i < this.data.photoArr.length; i++) {
      var item = this.data.photoArr[i]
      console.log("分享图片链接：", item)
      if(item.pass == '1') {
        return item.url
      }
    }
    return this.data.userInfo.avatar
  }

})